home *** CD-ROM | disk | FTP | other *** search
- #define N 10
-
- /*****************************************************************************
- * simul() *
- *****************************************************************************
- * DESCRIPTION: A function to solve a system of simultaneous linear *
- * equations by the Gauss-Jordan elimination method. *
- * *
- * SYNOPSIS: simul(m_in, m_out, n); *
- * int n; How many equations *
- * double *m_in; Points to a (N by N+1) matrix of *
- * coefficients. (N is #defined at *
- * compile time and must be the same *
- * for both this function and its *
- * caller. simul() destroys m_in. *
- * double *m_out; Points to (N by 1) array where *
- * result will be placed. *
- * *
- * EXAMPLE: To solve the system: *
- * *
- * 3x + 5y - z = 3 *
- * -2x - 3y + 4z = 8 *
- * x - 2z = -4 *
- * *
- * Set n to 3 and then fill in the upper-left corner of m_in *
- * with: *
- * *
- * 3 5 -1 3 *
- * -2 -3 4 8 *
- * 1 0 -2 -4 *
- * *
- * The result will then appear in the first three elements of *
- * m_out. *
- * *
- * REVISIONS: 19 DEC 88 - RAC - Original code *
- *****************************************************************************/
-
- simul(m_in, m_out, n)
- double m_in[N][N+1], m_out[N];
- int n;
- {
- int top_row; /* Row we're working on */
- int row; /* Generic row index */
- int col; /* Generic column index */
- double temp;
-
- for (top_row=0; top_row<n; top_row++) { /* For each row ... */
- for (row=top_row; row<n; row++) /* Scan from current row to */
- if (m_in[row][top_row] != 0.0) /* last row for a non-zero */
- break; /* entry the "rowth" column */
- if (m_in[row][top_row] != 0.0) { /* If such a row found ... */
- if (row != top_row) { /* and it's not the top one */
- for (col=0; col<=n; col++) { /* swap with the top one */
- temp = m_in[top_row][col];
- m_in[top_row][col] = m_in[row][col];
- m_in[row][col] = temp;
- } /* End swap */
- } /* End 'it's not the top' */
- temp = m_in[top_row][top_row]; /* Normalize current row */
- for (col=top_row; col<=n; col++)
- m_in[top_row][col] /= temp;
- for (row=top_row+1; row<n; row++) { /* Fix up rows below */
- temp = m_in[row][top_row] /
- m_in[top_row][top_row];
- for (col=top_row; col<=n; col++) {
- m_in[row][col] -=
- temp * m_in[top_row][col];
- }
- } /* End 'fix up rows below' */
- } /* End 'such a row found' */
- } /* End 'for each row' */
- for (row = n-1; row >= 0; row--) { /* For each row (again) */
- m_out[row] = m_in[row][n]; /* Figure out the answers! */
- for (col=row+1; col<n; col++)
- m_out[row] -=
- m_in[row][col] * m_out[col];
- } /* End 'for each row' */
- } /* End simul() */
-